﻿package kizzo.utils 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.setInterval;
	import flash.utils.clearInterval;
	
	public class BaseTweener extends EventDispatcher
	{
		public static const TWEEN_START:String = "TWEEN_START";
		public static const TWEEN_END:String = "TWEEN_END";

		public static const STOPPED:int = 0;		
		public static const RUNNING:int = 1;
		
		protected var steps:uint;
		protected var current_step:uint;
		protected var step_dir:int;
		
		protected var int_hnd:uint;
		
		protected var status:int;
		
		
		public function BaseTweener(steps:uint) 
		{
			this.steps = steps;
			this.current_step = 0;
			this.status = STOPPED;
			init();
			set_current(this.current_step);
		}
		
		protected function init():void
		{
			
		}
		
		public function step_to_start():void
		{
			this.status = RUNNING;
			clearInterval(this.int_hnd);
			this.step_dir = -1;
			this.int_hnd = setInterval(update, 20);			
		}
		
		public function step_to_end():void
		{
			this.status = RUNNING;
			clearInterval(this.int_hnd);
			this.step_dir = 1;
			this.int_hnd = setInterval(update, 20);			
		}
		
		private function update():void
		{			
			if (this.step_dir<0 && this.current_step == 0)
			{
				this.status = STOPPED;
				set_current(this.current_step);
				set_start();
				clearInterval(this.int_hnd);
			}
			else if (this.step_dir>0 && this.current_step == this.steps)
			{
				this.status = STOPPED;
				set_current(this.current_step);
				set_end();
				clearInterval(this.int_hnd);
			}
			else
			{
				this.current_step += this.step_dir;
				set_current(this.current_step);
			}			
		}
		
		
		
		protected function set_end():void
		{				
			dispatchEvent(new Event(TWEEN_END));
		}
		
		protected function set_start():void
		{			
			dispatchEvent(new Event(TWEEN_START));
		}
		
		protected function set_current(step:uint):void
		{
			
		}
		
		public function set_steps(steps:uint, current_step:uint):void
		{
			this.current_step = current_step;
			this.steps = steps;
		}
		
		public function stop():void
		{
			if (this.status == RUNNING)
			{
				this.status == STOPPED;
				clearInterval(this.int_hnd);
			}
		}
		
		public function get_status():int
		{
			return this.status;
		}
	}
	
}